package com.example.mindadinner.net;

import java.io.IOException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public abstract class RequestThread implements Runnable {
	public static final String BUNDLE_NAME_REQUEST_ID = "BUNDLE_NAME_REQUEST_ID";
	public static final String BUNDLE_NAME_RESULT = "BUNDLE_NAME_RESULT";
	private Request request;
	private long requestId = nextId();
	private static long lastId = System.currentTimeMillis();
	private Handler handler;

	/*
	 * 利用反射机制 根据request的子类类型建立相应的类型的Thread
	 */
	public RequestThread(Request request, Handler handler) {
		this.request = request;
		this.handler = handler;
	}

	@Override
	public void run() {
		try {
			internalRun();
		} catch (IOException e) {
			sendNetErrMessage(e);
		} catch (ApiException e) {
			sendApiException(e);
		}
	}

	private void sendMessage(RequestResult result) {
		if (handler == null) {
			return;
		}
		final Message message = handler.obtainMessage();
		final Bundle bundle = new Bundle();
		bundle.putLong(BUNDLE_NAME_REQUEST_ID, requestId);
		if (result != null) {
			bundle.putSerializable(BUNDLE_NAME_RESULT, result);
		}
		message.obj = bundle;
		handler.sendMessage(message);
	}

	protected void sendSuccessMessage(Response response) {
		sendMessage(new SuccessRequestResult(response));
	}

	protected void sendNetErrMessage(Exception e) {
		sendMessage(new NetErrRequestResult(e));
	}

	protected void sendApiException(ApiException e) {
		sendMessage(new ApiErrResult(e));
	}

	public long getRequestId() {
		return requestId;
	}

	public Request getRequest() {
		return request;
	}

	protected abstract void internalRun() throws IOException, ApiException;

	private static synchronized long nextId() {
		long now = System.currentTimeMillis();
		if (now <= lastId) {
			now = lastId + 1;
		}
		lastId = now;
		return now;
	}

}
